<template>
  <div class="home">
    <div>
      <van-field
        v-model="params.prompt"
        name="问题"
        label="问题"
        placeholder="请输入问题"
        :rules="[{ required: true }]"
      />
      <div class="btn">
        <van-button
          round
          class="mybtn"
          block
          type="primary"
          loading-text="搜索中..."
          @click="searchClick"
          >搜索</van-button
        >
        <van-button round class="mybtn" block type="info" @click="reset">重置</van-button>
      </div>
    </div>

    <div class="content">{{ value }}</div>
  </div>
</template>

<script>
let disconnectBtn = document.getElementById('disconnectSSE')
let sse
export default {
  components: {},
  data() {
    //这里存放数据
    return {
      params: {
        prompt: '',
        id: '12123'
      },
      value: '',
      loading: false
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //方法集合
  methods: {
    // 搜索
    searchClick() {
      if (!this.params.prompt) {
        return this.$toast('请输入问题')
      }
      this.value = ''
      this.searchFn()
    },
    // 请求
    async searchFn() {
      this.loading = true
      // eslint-disable-next-line no-unused-vars
      let text = ''
      let uuid_str = '8888'
      const eventSource = new EventSource(
        'http://localhost:8080/chat/chatGpt?id=' + uuid_str + '&prompt=' + this.params.prompt
      )

      eventSource.onopen = event => {
        console.log('onopen', event.readyState, event.target)
        sse = event.target
      }

      eventSource.onmessage = event => {
        if (event.data === '[DONE]') {
          text = ''
          if (sse) {
            sse.close()
          }
          return
        }
        let json_data = JSON.parse(event.data)
        if (json_data.delta.content == null || json_data.delta.content === 'null') {
          text = ''
          return
        }
        this.value = this.value + json_data.delta.content
      }

      eventSource.onerror = event => {
        console.log('onerror', event)
        alert('服务异常请重试并联系开发者！')
        if (event.readyState === EventSource.CLOSED) {
          console.log('connection is closed')
        } else {
          console.log('Error occured', event)
        }
        event.target.close()
      }

      eventSource.addEventListener('customEventName', event => {
        console.log('Message id is ' + event.lastEventId)
      })
    },
    // 重置
    reset() {
      this.params.prompt = ''
      this.value = ''
      if (sse) {
        sse.close()
      }
    },
    uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-'

      var uuid = s.join('')
      return uuid
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {} //生命周期 - 销毁完成
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
